<template>
  <div class="main">
    <!-- <div>
      <span @click="tiggle(1)">1</span> &nbsp;
      <span @click="tiggle(2)">2</span>&nbsp;
      <span @click="tiggle(5)">5</span>&nbsp;
      <span @click="tiggle('1D')">1D</span>&nbsp;
      <span @click="tiggle('1W')">1W</span>
      <span @click="tiggle('1W')">添加数据</span>

    </div> -->
    <div id="chartContainer" :class="[layout.isOnEnd ? 'end' : '']"></div>
    <div class="mask" v-if="ismask">
      <Loading></Loading>
    </div>
    <div class="charts_type ">
      <span class="zip" :class="[tradingView.chartsType == 'Chart' ? 'avtive' : '']" @click="changeChart">{{
      $t("message.CoinState.base")
    }}</span>
      <span class="zip" :class="[tradingView.chartsType == 'TradingView' ? 'avtive' : '']">TradingView</span>
    </div>
    <div class="mask_image" @click="getPng($event)">
    </div>
    <JLock :close="true"></JLock>

  </div>
</template>

<script setup lang="ts">

import { onMounted, getCurrentInstance, ref, onActivated, onDeactivated, onUnmounted } from 'vue';
// import datafeeds from "./datafeeds/datafees"
import datafeeds from "./detafeeds"
import { makeApiRequest, generateSymbol, parseFullSymbol } from './helpers.js';
import { useTradingView } from '@/stores/tradingVIew';
import { Conn } from "@/connetion/Conn";
import { Bus, CHART_KLINE_SUBSCRIBE_TIME, KLINE_RESET, TRADINGVIEW_KLINE, TRADINGVIEW_KLINE_SUBSCRIBE } from '@/connetion/Bus';
import { useLayout } from '@/stores/layout';
import { shage, shage1 } from "./config"
import { temp11 } from "./configTest"
import { IPineStudyResult, LibraryPineStudy, LibraryPineStudyConstructor, StudyMetaInfo } from './charting_library/charting_library';
import { useComm } from "./comm";
import { watch } from 'vue';
import { useKline } from '@/stores/kline';
import { concat } from 'ethers/lib/utils';
import JLock from "@/components/j-lock/index.vue";
import { calcLine } from "./calcLine"
import Loading from "@/components/chart/loading/index.vue";
import { YShare } from '../y-share/script';
import TimeTips from "@/components/timeTips/index.vue";
import { useRoute } from "vue-router";
const route = useRoute();

let kline = useKline()
const userComm = useComm('', '', () => { }, '')
interface CustomIndicator {
  readonly name: string;
  readonly metainfo: StudyMetaInfo;
  readonly constructor: LibraryPineStudyConstructor<IPineStudyResult> | ((this: LibraryPineStudy<IPineStudyResult>) => void);
}
const props = defineProps({
  height: {
    type: String,
    default: '700'
  }
})
let layout = useLayout()
let tradingView = useTradingView()
let datafeedsData: any
let tvWidget: any
let zhouqi: any = localStorage.getItem('resolution') || '1D'
let symbol: any = localStorage.getItem('K_TYPE') || 'ETHUSDT'
let interval = localStorage.getItem('K_TIME') || 'MN5'
let fristData = []
let data = []
let allData = [];
let ismask = ref(false)
let cycle: any = {
  '1': "MN1",
  '5': "MN5",
  '15': "MN15",
  '30': "MN30",
  '60': "H1",
  '240': "H4",
  '1D': "D1",
  '1W': "W1",
}

function getSymbolName() {
  if (location.pathname.includes("/coin/")) {
    return location.pathname.split("/coin/").pop();
  }

  return localStorage.getItem('K_TYPE') || 'ETHUSDT'
}

onActivated(() => {
  if (!tvWidget) {
    initTrading()

  }

})
onDeactivated(() => {
  tvWidget.remove();
  console.log(tvWidget.remove())
  tvWidget = null;
})
function changeChart() {
  tradingView.changeType('Chart')
  layout.toggleChartsLoading(true)
  let symbolC: string = localStorage.getItem('K_TYPE') || ''
  if (route.params.id) {
    symbolC = route.params.id
  }
  kline.changeCurCoinByName(symbolC)
}
onMounted(() => {
  const instance = getCurrentInstance();
  // console.log(instance)
  if (zhouqi == 'undefined') {
    zhouqi = '1D'
  }
  console.log("coin detail onMounted", route, route.params.id);
  if (route.params.id) {
    symbol = route.params.id
  }
  datafeedsData = new datafeeds(trading)
  if (!tvWidget) {
    initTrading()
  }
  Conn.ins.init({ "symbol": symbol, "topic": "kline", "interval": interval });
  // console.log(datafeedsData, 11111)

})

onUnmounted(() => {
  tvWidget.remove();
  console.log(tvWidget.remove())
  tvWidget = null;
})
// 获取截图
async function getPng(e: Event) {
  const screenshotCanvas = await tvWidget.takeClientScreenshot();
  // document.getElementById("shuiying")!.style.visibility = "visible";
  // const canvas = await html2canvas(char);
  // document.body.appendChild(canvas);
  YShare.open(screenshotCanvas, "Share or download chart image", "Chart");
}
// 切换周期
function tiggle(resolution) {
  // tvWidget.chart().setResolution(resolution);
  // zhouqi.value = resolution
  // let obj = {
  //   time: new Date().getTime(),
  //   close: 2000 + Math.random() * 5,
  //   open: 4 + Math.random() * 5,
  //   high: 4 + Math.random() * 5,
  //   low: 400 + Math.random() * 5,
  //   volume: 100000 * Math.random()
  // }

  // console.log(tradingView.subscriberList)
  // tradingView.subscriberList.callback(obj)
  // tvWidget.activeChart().resetData();
  // tvWidget.activeChart().setSymbol('ETC/USDT');
  //   tvWidget.activeChart().setVisibleRange(
  //     { from: Date.UTC(2023, 6, 12, 13, 30) / 1000},
  //     { applyDefaultRightMargin: true }
  // )
  // let len = window.WTTbarData.length
  // let fristData = window.WTTbarData
  // tvWidget.chart().setVisibleRange({ from: fristData[len > 100 ? len - 100 : 0].startTime / 1000, to: fristData[len - 1].startTime / 1000 });
}
let trading = {
  // 切换时间或币种是订阅
  async subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
    let temp = symbolInfo.name.replace("/", "");
    Bus.emit(TRADINGVIEW_KLINE, { symbol: temp, interval: cycle[resolution] });
    let timeType = location.pathname.includes("/coin") ? "K_TIME_COIN" : "K_TIME";
    // 记录订阅的币队时间
    localStorage.setItem(timeType, cycle[resolution]);
    localStorage.setItem("resolution", resolution);

  },
  // 获取数据
  async getBars(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback, parsedSymbol) {
    console.log("getBarsgetBarsgetBarsgetBars")
    const { from, to, firstDataRequest } = periodParams;

    console.log(symbolInfo, resolution, periodParams, parsedSymbol, zhouqi, "parsedSymbolparsedSymbol")
    let isMore = false
    zhouqi = resolution
    const urlParameters = {
      e: "Binance",
      fsym: parsedSymbol.fromSymbol,
      tsym: parsedSymbol.toSymbol,
      toTs: to,
      limit: 2000,
    };
    const query = Object.keys(urlParameters)
      .map(name => `${name}=${encodeURIComponent(urlParameters[name])}`)
      .join('&');
    try {
      if (firstDataRequest) {
        allData = []
        data = await makeApiRequest(`/api/stream/bar/${parsedSymbol.fromSymbol}USDT/list?interval=${cycle[zhouqi]}&limit=1000`);
        fristData = data.data
        allData = data.data.concat(allData);
      } else {
        if (this.chartData[0]?.time <= tradingView.tradingViewData[0].startTime) {
          data = await makeApiRequest(`/api/stream/bar/${parsedSymbol.fromSymbol}USDT/list?interval=${cycle[zhouqi]}&limit=1000&endTime=${this.chartData[0]?.time || ''}`);
          allData = data.data.concat(allData);
        }
        else {
          onHistoryCallback([], { noData: true });
          return
        }
      }
      window.WTTbarData = allData;
      let dd = calcLine(allData)
      tradingView.tradingViewData = data.data
      if (!data.success || data.data.length === 0) {
        onHistoryCallback([], { noData: true });
        return;
      }
      let bars = [];
      data.data.forEach(bar => {
        if ((bar.startTime / 1000) >= from || (bar.startTime / 1000) < to) {
          // console.log(bar)
          bars = [...bars, {
            time: bar.startTime,
            low: bar.low,
            high: bar.high,
            open: bar.open,
            close: bar.close,
            volume: bar.volume

          }];
        }
      });

      this.chartData = JSON.parse(JSON.stringify(bars))
      if (data.data.length < 1000) {
        isMore = true
        // console.log("没有更多数据了", isMore)
      }
      // console.log(bars, "barsbars")
      if (bars[bars.length - 1].time == allData[0].startTime) {
        onHistoryCallback([], { noData: true });
      }
      else {
        onHistoryCallback(bars, { noData: isMore });
      }
    } catch (error) {
      console.log('[getBars]: Get error', error);
      onErrorCallback(error);
    }
  }
}
function isNumeric(str) {
  return !isNaN(Number(str));
}
// 数组去空
function replaceEmptyWithNaN(arr) {
  return arr.map((value) => {
    if (Array.isArray(value)) {
      // 递归处理嵌套数组
      return replaceEmptyWithNaN(value);
    }
    // 替换空值为 NaN
    return value === '' ? NaN : value;
  });
}

// 初始化tradingView
function initTrading() {
  let tradingSymbol = "";
  console.warn("######## tradingSymbol", tradingSymbol)
  if (!symbol.includes('/')) {
    tradingSymbol = symbol.replace('USDT', '/USDT');
  }
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
  tvWidget = new TradingView.widget({
    // width: 200,
    // height: 800,
    autosize: true,
    theme: "dark",
    disabled_features: [
      // "left_toolbar",
      // "header_symbol_search",
      // "source_selection_markers",
      // "adaptive_logo",
      // "header_screenshot",
      // "volume_force_overlay",
      // "use_localstorage_for_settings",

      // "header_resolutions", //！！！！！隐藏头部周期 记得打开
      "header_fullscreen_button",
      "edit_buttons_in_legend",
      "legend_context_menu",
      "header_symbol_search",
      "timeframes_toolbar",
      "header_compare",
      // "use_localstorage_for_settings",
      "show_object_tree",
      "symbol_search_hot_key"
    ],
    enabled_features: ["two_character_bar_marks_labels", "show_hide_button_in_legend", "format_button_in_legend", "delete_button_in_legend"],
    timezone: timezone || "UTC",
    favorites: {
      intervals: ["5", "15", "1D"],
      // chartTypes: ["Area", "Line"]
    },
    container: 'chartContainer',
    locale: localStorage.getItem('language') == 'zh' ? 'zh_TW' : localStorage.getItem('language') || "en",
    // toolbar_bg:"#1c1f25",
    // supported_resolutions: [ '1', '2', '5', '15', '30', '60', '120', '240', '1D', '1W', '1M'],
    library_path: '/asset/js/charting_library/charting_library.standalone.js',
    datafeed: datafeedsData,
    symbol: tradingSymbol,
    interval: zhouqi,
    loading_screen: { backgroundColor: 'black', foregroundColor: 'black' },
    // fullscreen: true,
    debug: false,
    // custom_css_url: "tradingView.css",
    overrides: {
      // "mainSeriesProperties.showBottomPane": true,
      "mainSeriesProperties.candleStyle.upColor": "#2dc08e",//买入颜色
      "mainSeriesProperties.candleStyle.downColor": "#f92855",//卖出颜色	mainSeriesProperties.candleStyle
      "mainSeriesProperties.candleStyle.candleWidth": 500,
      // "paneProperties.background":"#1c1f25",
      // "scalesProperties.lineColor": "#2e3345",
      //   "scalesProperties.textColor": "#8f98ad",
      //   "scalesProperties.scaleSeriesOnly": false,
      //   "mainSeriesProperties.priceAxisProperties.autoScale": true,
      //   "mainSeriesProperties.priceAxisProperties.autoScaleDisabled": false,
      //   "mainSeriesProperties.priceAxisProperties.percentage": false,
      //   "mainSeriesProperties.priceAxisProperties.percentageDisabled": false,
      //   "mainSeriesProperties.priceAxisProperties.log": false,
      //   "mainSeriesProperties.priceAxisProperties.logDisabled": false,
      //   "paneProperties.vertGridProperties.color": "#202328",
      //   "paneProperties.horzGridProperties.color": "#202328",
    },
    custom_formatters: {
      // timeFormatter: {
      //   format: (date) => {
      //     const _format_str = '%h:%m';
      //     return _format_str
      //       .replace('%h', date.getUTCHours(), 2)
      //       .replace('%m', date.getUTCMinutes(), 2)
      //       .replace('%s', date.getUTCSeconds(), 2);
      //   }
      // },
      dateFormatter: {
        format: (date) => {
          return date.getUTCFullYear() + '-' + (date.getUTCMonth() + 1 < 10 ? '0' + (date.getUTCMonth() + 1) : date.getUTCMonth() + 1) + '-' + (date.getUTCDate() < 10 ? '0' + date.getUTCDate() : date.getUTCDate());
        }
      },
    },
    custom_indicators_getter: function (PineJS) {
      return Promise.resolve([
        shage(PineJS, tradingSymbol),
        // temp11
        // shage1(PineJS)
      ]);
    },
    // custom_indicators_getter?: (PineJS: PineJS) => Promise<readonly CustomIndicator[]>
  });
  tvWidget.onChartReady(function () {
    setTimeout(() => {
      ismask.value = false

    }, 160)
    // tradingView.setInterval()
    layout.toggleChartsLoading(false)

    console.log(tvWidget.activeChart().getTimeScale(), tvWidget.chart(), "tvWidgettvWidget")
    // window.WTTbarData = tvWidget.activeChart().getSeries().data().m_bars._items

    let len = fristData.length;
    // tvWidget.chart().setVisibleRange({ from: fristData[len > 100 ? len - 100 : 0].startTime / 1000, to: fristData[len - 1].startTime / 1000 });

    tvWidget.chart().createStudy('CVLINE', true, false);
    tvWidget.chart().createStudy('Volume', true)
    tvWidget.chart().createStudy('Volume Profile Visible Range', true)
    const timeScaleAPI = tvWidget.activeChart().getTimeScale();
    timeScaleAPI.setRightOffset(50);
    timeScaleAPI.setBarSpacing(10);
    //     tvWidget.chart().getSeries().setChartStyleProperties(1, {
    //     upColor: '#2dc08e',
    //     downColor: '#f92855',
    // });
    // tvWidget.takeScreenshot().then(data => {
    //   // 处理生成的快照数据
    //   console.log('快照数据:', data);
    // });
    Bus.emit(KLINE_RESET);

    tvWidget.subscribe("time_interval", (res) => {
      tradingView.setInterval()
      ismask.value = true
      setTimeout(() => {
        console.log(res)
        zhouqi = res.label
        tvWidget.remove();
        console.log(tvWidget.remove())
        tvWidget = null;
        initTrading()
      }, 160)

    });

  });
  //   tvWidget.headerReady().then(function() {
  //     var button = tvWidget.createButton({align:'right'});
  //     button.setAttribute('title', '基础版');
  //     button.addEventListener('click', function() {

  //       tradingView.changeType('Chart')
  //     });
  //     button.textContent = '基础版';
  // });

  let cvline = ""
  window.testDraw = async function () {
    window.useTest = true
  }

  window.checkDataLink = function () {
    let list = window.WTTbarData;
    // let space = 30 * 60 * 1000;
    let space = 1900000;
    let well = true;
    list.forEach((v, i) => {
      if (i > 0) {
        let ct = v.startTime;
        let pt = list[i - 1].startTime;
        let t = ct - pt;
        if (t > space) {
          console.error("@@@@@@@ 断点", i, new Date(ct));
          well = false;
        }
      }
    })
    console.error(well ? "没有断线" : "有断线")
  }

  window.checkDataLink2 = function () {
    let list = tvWidget.activeChart().getSeries().data().m_bars._items
    let space = 1900000;
    let well = true;
    list.forEach((v, i) => {
      if (i > 0) {
        let ct = v.timeMs;
        let pt = list[i - 1].timeMs;
        let t = ct - pt;
        if (t > space) {
          console.error("@@@@@@@ 断点", i, new Date(ct), t);
          well = false;
        }
      }
    })
    console.error(well ? "没有断线" : "有断线")
  }

  window.findTimeId = function (str) {
    let n = str.replace(/\D/g, "");
    console.log(n);
    let list = window.WTTbarData;
    let t = list.findIndex(i => i.timeId == n);
    console.log("查找索引", t)
  }

  Bus.on(TRADINGVIEW_KLINE_SUBSCRIBE, (e: any) => {
    try {
      window.WTTLineData = []
      window.WTTbarData = []
      if (tvWidget) {
        ismask.value = true
        setTimeout(() => {
          symbol = e.replace('/USDT', 'USDT');
          tvWidget.onChartReady(function () {
            tvWidget.remove();
            console.log(tvWidget.remove())
            tvWidget = null;
            initTrading()
            // tvWidget.activeChart().setSymbol(e);

          })
        }, 160)

      }
    } catch (e) {
      console.log(e)
    }

  });
}
</script>
<style scoped lang="less">
.main {
  height: 100%;
  position: relative;
}

.end {
  pointer-events: none;
}

.mask {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 1);
  z-index: 2;
}

.mask_image {
  position: absolute;
  top: 0;
  right: 10px;
  width: 40px;
  height: 38px;
  cursor: pointer;
  border-radius: 2px;
  background-color: transparent;

  &:hover {
    background-color: rgba(255, 255, 255, 0.1);

  }
}

.charts_type {
  position: absolute;
  top: 0;
  right: 140px;
  /* width: 100px; */
  height: 38px;
  background-color: transparent;
  display: flex;
  align-items: center;
  color: #D1D4DC;
  font-size: 14px;
  gap: 10px;
  cursor: pointer;

  .avtive {
    color: #fcc235 !important;
  }

  span {
    font-family: var(--font-family);
    padding-top: 2px;
  }
}

.zip:hover {
  color: #fff;
}

.test {
  width: 100%;
  background-color: black;

}

#chartContainer {
  /* width: 1000px; */
  /* height: 80vh; */
  height: 100%;
  margin: 0 var(--space) 0;
}
</style>